package com.warm.spring.config;


import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.warm.spring.mvc.interceptor.MyInterceptorA;
import com.warm.spring.mvc.interceptor.MyInterceptorB;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @Date: 2019/11/25 14:57
 * @Author: LChuang
 * @Description: mvc 配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
     * 多个拦截器组成一个拦截器链
     * addPathPatterns 用于添加拦截规则
     * excludePathPatterns 用户排除拦截
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptorA()).addPathPatterns("/**");
        registry.addInterceptor(new MyInterceptorB()).addPathPatterns("/**");
    }

    /**
     * 配置消息转换器--使用alibaba的fastjson
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 1. define message convert object
        FastJsonHttpMessageConverter fastJsonHttpMessageConvert = new FastJsonHttpMessageConverter();
        //2. add fastJson configure, for example : do you want to format the return of JSON data
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteDateUseDateFormat);
        //3. handle Chinese random code
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //4. add config in convert
        fastJsonHttpMessageConvert.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConvert.setFastJsonConfig(fastJsonConfig);
        //5. add convert to converts
        converters.add(fastJsonHttpMessageConvert);
    }
}
